package com.chaofan.sell.controller;

import com.chaofan.sell.dto.OrderDTO;
import com.chaofan.sell.enums.Result;
import com.chaofan.sell.exception.SellException;
import com.chaofan.sell.service.OrderService;
import com.chaofan.sell.service.PayService;
import com.lly835.bestpay.model.PayResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * @author: Fairy
 * @date: 2021/9/15
 */
@Controller
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PayService payService;

    /**
     * 创建微信预支付订单
     *
     * @param orderId   订单号
     * @param returnUrl 回调url
     * @param map       支付响应
     * @return ModelAndView
     */
    @GetMapping("/create")
    public ModelAndView create(@RequestParam("orderId") String orderId,
                               @RequestParam("returnUrl") String returnUrl,
                               Map<String, Object> map) {
        //1.查询订单
        OrderDTO orderDTO = orderService.findOne(orderId);
        if (orderDTO == null) {
            throw new SellException(Result.ORDER_NOT_EXISTS);
        }
        //2.发起支付
        PayResponse payResponse = payService.create(orderDTO);
        map.put("payResponse", payResponse);
        map.put("returnUrl", returnUrl);

        return new ModelAndView("pay/create", map);
    }

    @PostMapping("/notify")
    public ModelAndView notify(@RequestBody String notifyData) {
        PayResponse notify = payService.notify(notifyData);
        //返回处理结果

        return new ModelAndView("pay/success");
    }
}
